package com.example.content.manager

import android.app.Activity
import android.app.Application
import android.content.Intent
import android.os.Bundle
import com.example.content.KEY_FRAGMENT
import com.example.content.activity.CommonActivity

/**
 * Created by zhudongao
 * Desc
 * Date 2020/10/7
 */
object ActivityMgr : Application.ActivityLifecycleCallbacks {

    val activities = mutableListOf<Activity>()
    var resumeActivity: Activity? = null

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        resumeActivity = activity
        activities.add(activity)
    }

    override fun onActivityStarted(activity: Activity) {
        resumeActivity = activity
    }

    override fun onActivityResumed(activity: Activity) {
        resumeActivity = activity
    }

    override fun onActivityPaused(activity: Activity) {

    }

    override fun onActivityStopped(activity: Activity) {

    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {

    }

    override fun onActivityDestroyed(activity: Activity) {
        activities.remove(activity)
    }

    fun startActivity(clazz: Class<out Activity>, bundle: Bundle) {
        val intent = Intent(resumeActivity, clazz)
        intent.putExtras(bundle)
        resumeActivity?.startActivity(intent)
    }

    fun startActivity(clazz: Class<out Activity>) {
        resumeActivity?.startActivity(Intent(resumeActivity, clazz))
    }

    fun startFragment(bundle: Bundle) {
        val intent = Intent(resumeActivity, CommonActivity::class.java)
        intent.replaceExtras(bundle)
        resumeActivity?.startActivity(intent)
    }

    fun startFragment(fragmentType: Int) {
        val intent = Intent(resumeActivity, CommonActivity::class.java)
        intent.putExtra(KEY_FRAGMENT, fragmentType)
        resumeActivity?.startActivity(intent)
    }

    /**
     * 结束所有activity 除了指定的
     */
    fun finishAllBut(activity: Activity) {
        activities.forEach {
            if (it != activity) {
                it.finish()
            }
        }
    }

    fun finishAll() {
        activities.forEach {
            it.finish()
        }
    }
}